import { open,save  } from '@tauri-apps/plugin-dialog'
import { readTextFile,writeTextFile  } from '@tauri-apps/plugin-fs'
import * as path from '@tauri-apps/api/path';


export const readConfig = async () => {
  try {
    const home = await path.homeDir();
    const config = await readTextFile(await path.join(home, 'config.txt'))
    return config.trim().split('\n');
  } catch (err) {
    console.error('读取配置文件失败:', err);
    return [];
  }
}


export const selectAndReadFile = () => new Promise(async (resolve, reject) => {
  try {
    const selected = await open({
      filters: [{
        name: '文本文件',
        extensions: ['txt']
      }]
    });
    if (selected) {
      // 读取选中文件的内容
      const content = await readTextFile(selected)
      resolve(content);
    }
  } catch (err) {
    reject(err)
  }
});

export const selectAndWriteFile = (content,filename='document.txt') => new Promise(async (resolve, reject) => {
  try {
    const selected = await save({
      title: '保存文本文件',
      defaultPath: filename,
      filters: [
        {
          name: '文本文件',
          extensions: ['txt']
        },
        {
          name: 'All Files',
          extensions: ['*']
        }
      ]
    });
    if (selected) {
      // 写入选中文件的内容
      await writeTextFile(selected, content)
      resolve(selected);
    }else {
      reject('用户取消了保存操作')
    }
  } catch (err) {
    reject(err)
  }
});
